package com.dmgis.qxfw.dataservice.businessservice.qxinfo.controller;


import com.dmgis.qxfw.dataservice.businessservice.dmgis_mongodb_srv.common.util.FileUtil;
import com.dmgis.qxfw.dataservice.businessservice.dmgis_mongodb_srv.dataservice.service.Impl.MongoService1;
import com.dmgis.qxfw.dataservice.businessservice.qxinfo.service.IQxInfoService;
import com.dmgis.qxfw.dataservice.commonservice.common.DbConfig;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/qxinfo")
public class DocFileController{

	MongoService1 ms = new MongoService1();

	@Resource
	private IQxInfoService qxInfoService;
	/**
	 * 下载文件
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping(value = "download", method = RequestMethod.GET)
	public void download(HttpServletRequest request, HttpServletResponse response) throws IOException {

		// 1.获取要下载的文件的绝对路径
		String docpath = request.getParameter("docpath");
		String docid = qxInfoService.getQxWarnDoc(docpath);

		String servicePath = "";// 服务器文件

		String urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp\\QxWarning\\";// 临时文件目录
		FileUtil.mkDirs(urlpath);// 创建文件夹，生成多级目录
		FileUtil.ClearTempFiles(urlpath, 1000);// 清除缓存

		// 2.获取要下载的文件名
		String fileName = docpath;// 文件名
		String doctype = fileName.split("\\.")[fileName.split("\\.").length - 1];// 文件类型
		String pdfPath = "";
		if (doctype.contains("doc")) {
			pdfPath = urlpath + fileName.replace(doctype, "pdf");
			File pdfFile = new File(pdfPath);
			if (pdfFile.exists()) {
				servicePath = "Temp\\QxWarning\\" + fileName.replace(doctype, "pdf");
			} else {
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("id", docid);
				map.put("table_name", "base_product");
				map.put("collectionName", "pdf_file");
				map.put("advCode", DbConfig.advCode);
				byte[] data = ms.selectData(map);
				if (data == null) {
					servicePath =  "";
				}else{
					FileUtil.bytesToFile(data, pdfPath);
					servicePath = "Temp\\QxWarning\\" + fileName.replace(doctype, "pdf");
				}
			}
		}
		if(!servicePath.equals("")){
			response.reset();
			response.setContentType("application/octet-stream");
			// 3.设置content-disposition响应头控制浏览器以下载的形式打开文件
			response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
			InputStream in = new FileInputStream(pdfPath);// 获取文件输入流
			int len = 0;
			byte[] buffer = new byte[1024];
			OutputStream out = response.getOutputStream();
			while ((len = in.read(buffer)) > 0) {
				out.write(buffer, 0, len);// 将缓冲区的数据输出到客户端浏览器
			}
			in.close();
		}else{
			response.setContentType("text/html; charset=UTF-8"); //转码
		    PrintWriter out = response.getWriter();
		    out.flush();
		    out.println("<script>");
		    out.println("alert('文件不存在，无法下载文件！');");
		    out.println("history.back();");
		    out.println("</script>");
		}
	}

	/**
	 * 下载雷电文件
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping(value = "downloadLD", method = RequestMethod.GET)
	public void downloadLD(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String id = request.getParameter("id");// 时间
		String productname = request.getParameter("productname");// 时间
		String servicePath = "";// 服务器文件
		String urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp\\LDfile\\";// 临时文件目录
		FileUtil.mkDirs(urlpath);// 创建文件夹，生成多级目录
		FileUtil.ClearTempFiles(urlpath, 1000);// 清除缓存
		String fileName = productname;// 文件名
		String doctype = fileName.split("\\.")[fileName.split("\\.").length - 1];// 文件类型
		String pdfPath = "";
		if (doctype.contains("doc")) {
			pdfPath = urlpath + fileName.replace(doctype, "pdf");
			File pdfFile = new File(pdfPath);
			if (pdfFile.exists()) {
				servicePath = "Temp\\LDfile\\" + fileName.replace(doctype, "pdf");
			} else {
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("id", id);
				map.put("table_name", "base_product");
				map.put("collectionName", "pdf_file");
				map.put("advCode", DbConfig.advCode);
				byte[] data = ms.selectData(map);
				//byte[] data = HttpRequest.get(DbConfig.mongoSelectUrl, map, true).bytes();
				// 下载doc文件
				if (data == null) {
					servicePath =  "";
				}
				FileUtil.bytesToFile(data, pdfPath);
				servicePath = "Temp\\LDfile\\" + fileName.replace(doctype, "pdf");
			}
		}
		if(!servicePath.equals("")){
			response.reset();
			response.setContentType("application/octet-stream");
			// 3.设置content-disposition响应头控制浏览器以下载的形式打开文件
			response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
			InputStream in = new FileInputStream(pdfPath);// 获取文件输入流
			int len = 0;
			byte[] buffer = new byte[1024];
			OutputStream out = response.getOutputStream();
			while ((len = in.read(buffer)) > 0) {
				out.write(buffer, 0, len);// 将缓冲区的数据输出到客户端浏览器
			}
			in.close();
		}else{
			response.setContentType("text/html; charset=UTF-8"); //转码
		    PrintWriter out = response.getWriter();
		    out.flush();
		    out.println("<script>");
		    out.println("alert('文件不存在，无法下载文件！');");
		    out.println("history.back();");
		    out.println("</script>");
		}
	}
}